import Vue from 'vue';
import Vuex from 'vuex';
import common from '@/common/common.js';
import Bluetooth from '@/common/bluetooth/bluetooth.js';
var bluetooth = new Bluetooth();
Vue.use(Vuex);

const store = new Vuex.Store({
	state: {
		screenWidth: 0,
		isLogin: false,
		userInfo: {},
		isOpenBle: false,
		bledd: false,
		connectDeviceId: '',
		connectDeviceInfo: {},
		devicesList: [],
		nickName: '',
		selectCouponList: [], // 下单选择商品用，可用优惠券列表
		selectCouponItem: {}, // 下单选择商品用，所选优惠券
		goodsIdList: [], // 优惠券过滤商品用，所选商品集合
		categoryIdList: [], // 优惠券过滤商品用，所选分类集合
	},
	getters: {
		getScreenWidth: (state) => state.screenWidth || 0,
		getNickName: (state) => state.nickName,
		getSelectCouponItem: (state) => state.selectCouponItem || {},
		getSelectCouponList: (state) => state.selectCouponList || [],
		getGoodsIdList: (state) => state.goodsIdList || [],
		getCategoryIdList: (state) => state.categoryIdList || []
	},
	mutations: {
		setScreenWidth(state, width) {
			state.screenWidth = width
		},
		setSelectCouponItem(state, item) {
			state.selectCouponItem = item
		},
		setSelectCouponList(state, list) {
			state.selectCouponList = list
		},
		cleanSelectCouponItem(state) {
			state.selectCouponItem = {}
		},
		cleanSelectCouponList(state) {
			state.selectCouponList = []
		},
		/** 商品集合 */
		setGoodsIdList(state, list) {
			state.goodsIdList = list
		},
		cleanGoodsIdList(state) {
			state.goodsIdList = []
		},
		/** 分类集合 */
		setCategoryIdList(state, list) {
			state.categoryIdList = list
		},
		cleanCategoryIdList(state) {
			state.categoryIdList = []
		},

		setNickName(state, name) {
			state.nickName = name;
		},

		loginSaveUserInfo(state, provider) {
			state.isLogin = true;
			state.userInfo = provider;
			uni.setStorage({
				key: 'userInfo',
				data: provider,
			});
		},
		logout(state) {
			state.isLogin = false;
			state.userInfo = {};
			uni.removeStorage({
				key: 'userInfo',
			});
		},
		setBledd(state, bledd) {
			state.bledd = bledd;
		},
		setConnectDeviceId(state, deviceId) {
			state.connectDeviceId = deviceId;
		},
		setConnectDeviceInfo(state, info) {
			state.connectDeviceInfo = info;
		},
		/**
		 * 设置devicesList
		 * @param {Object} state
		 * @param {Array} devicesList
		 */
		setDevicesList(state, devicesList) {
			state.devicesList = devicesList;
		},
		setOpenBle(state, status) {
			state.isOpenBle = status;
		},

		/**
		 * 关闭蓝牙
		 */
		closeBluetoothAdapter(state) {
			bluetooth.closeBluetoothAdapter();
			state.isOpenBle = false;
			state.bledd = false;
			state.connectDeviceId = ''
			state.connectDeviceInfo = {}
		},
	},
	actions: {
		/**
		 * 初始化蓝牙
		 */
		openBluetoothAdapter({
			commit,
			dispatch,
			state
		}) {
			return new Promise(async (resolve, reject) => {
				try {
					var isOpenBle = await bluetooth.openBluetoothAdapter();
					console.log('初始化蓝牙', isOpenBle);
					commit('setOpenBle', true);
					common.showToast('蓝牙初始化成功');
					resolve()
				} catch (err) {
					console.warn('errr', err);
					commit('setOpenBle', false);
					if (err.errCode) {
						common.showToast(bluetooth.bleerrcode(err.errCode));
					} else {
						uni.openBluetoothAdapter({
							fail(err) {
								console.warn('Bluetooth fail err', err)
								if (err.errno === 103) {
									common.showToast('蓝牙初始化失败，请点击右上角胶囊设置允许蓝牙使用');
								} else {
									common.showToast('蓝牙连接失败，请检查蓝牙后使用');
								}
							}
						})
					}
					reject()
				}
			})
		},
		/**
		 * 开启蓝牙搜索
		 */
		startBluetoothDevicesDiscovery({
			commit,
			dispatch,
			state
		}) {
			return new Promise(async (resolve, reject) => {
				console.log('开启蓝牙搜索');
				try {
					if (!state.isOpenBle) {
						return;
					}
					await bluetooth.startBluetoothDevicesDiscovery();
					commit('setBledd', true);
					dispatch('onBluetoothDeviceFound');
					commit('setDevicesList', []);
					resolve(true);
				} catch (err) {
					commit('setBledd', false);
					if (err.errCode) {
						common.showToast(bluetooth.bleerrcode(err.errCode));
					} else if (err.errMsg) {
						common.showToast(err.errMsg);
					}
					reject(err);
				}
			});
		},
		/**
		 * 关闭搜索
		 */
		stopBluetoothDevicesDiscovery({
			commit,
			state
		}) {
			return new Promise(async (resolve, reject) => {
				console.log('关闭蓝牙搜索');
				try {
					await bluetooth.stopBluetoothDevicesDiscovery();
					commit('setBledd', false);
					resolve(true);
				} catch (err) {
					commit('setBledd', false);
					if (err.errCode) {
						common.showToast(bluetooth.bleerrcode(err.errCode));
					} else if (err.errMsg) {
						common.showToast(err.errMsg);
					}
					reject(err);
				}
			});
		},
		/**
		 * 监听寻找到新设备的事件
		 */
		onBluetoothDeviceFound({
			commit,
			state
		}) {
			// console.log('监听寻找到新设备的事件');
			uni.onBluetoothDeviceFound((res) => {
				//不重复，有名称，就添加到devicesList中
				if (
					res.devices[0].name &&
					!state.devicesList.find((item) => item.deviceId === res.devices[0].deviceId)
				) {

					// devicesList.push(res.devices[0]);
					// console.log('结果 devicesList', devicesList);
					commit('setDevicesList', [...state.devicesList, res.devices[0]]);
				}
			});
		},
		/**
		 * 连接低功耗蓝牙设备
		 * @param {Object} item 设备信息
		 */
		createBLEConnection({
			commit
		}, item) {
			return new Promise(async (resolve, reject) => {
				try {
					await bluetooth.createBLEConnection(item.deviceId);
					commit('setConnectDeviceId', item.deviceId);
					commit('setConnectDeviceInfo', item);
					resolve(true);
				} catch (err) {
					reject(err);
				}
			});
		},
		/**
		 * 断开蓝牙
		 * @param {String} deviceId 蓝牙设备 id
		 */
		async closeBLEConnection(ten, deviceId) {
			return new Promise(async (resolve, reject) => {
				try {
					await bluetooth.closeBLEConnection(deviceId);
					commit('setConnectDeviceId', undefined);
					commit('setConnectDeviceInfo', {});
					resolve(true);
				} catch (err) {
					if (err.errCode != -1) {
						common.showToast(`${item.name}：` + bluetooth.bleerrcode(err.errCode));
					} else if (err.errMsg && err.errCode != -1) {
						common.showToast(`${item.name}：` + err.errMsg);
					} else {
						common.showToast(`${item.name}：`);
					}
					reject(err);
				}
			});
		},
		/**
		 * 启用设备的notify服务
		 * @param {String} deviceId 蓝牙设备 id
		 * @param {String} serviceId
		 * @param {String} characteristicId
		 */
		openNotify({
			dispatch
		}, {
			deviceId,
			serviceId,
			characteristicId
		}) {
			return new Promise(async (resolve, reject) => {
				try {
					await bluetooth.notifyBLECharacteristicValueChange(deviceId, serviceId,
						characteristicId);
					resolve(true);
				} catch (err) {
					if (err.errCode) {
						common.showToast(bluetooth.bleerrcode(err.errCode));
					} else if (err.errMsg) {
						common.showToast(err.errMsg);
					}
					reject(err);
				}
			});
		},
		/**
		 * 检测匹配设备服务
		 * @param {String} deviceId 蓝牙设备 id
		 * @param {String} serviceId
		 * @param {String} characteristicId
		 */
		checkDeviceService({
			dispatch
		}, {
			deviceId,
			serviceId,
			characteristicId
		}) {
			return new Promise(async (resolve, reject) => {
				try {
					await bluetooth.getBLEDeviceServices(deviceId, serviceId);
					await bluetooth.getBLEDeviceCharacteristics(deviceId, serviceId,
						characteristicId);
					resolve(true);
				} catch (err) {
					if (err.errCode) {
						common.showToast(bluetooth.bleerrcode(err.errCode));
					} else if (err.errMsg) {
						common.showToast(err.errMsg);
					}
					dispatch('closeBLEConnection', deviceId);
					reject(err);
				}
			});
		},
		/**
		 * 根据properti匹配对应操作权限的特征
		 * @param {String} deviceId 蓝牙设备 id
		 * @param [String,Array] properti 需要匹配的操作权限（write,read,notify,indicate）
		 */
		getProperti(ten, {
			deviceId,
			properti = 'write'
		}) {
			return new Promise(async (resolve, reject) => {
				try {
					var services = await bluetooth.getBLEDeviceServices(deviceId);
					if (services.length > 0) {
						for (var i = 0; i < services.length; i++) {
							if (services[i].isPrimary) {
								var res = await bluetooth.getBLEDeviceCharacteristics(deviceId,
									services[i].uuid);
								if (res.length > 0) {
									for (var s = 0; s < res.length; s++) {
										if (res[s].properties[properti]) {
											return resolve({
												characteristicId: res[s].uuid,
												serviceId: services[i].uuid,
											});
										}
									}
								}
							}
						}
						common.showToast(`该设备无${properti}权限，可能无法使用该功能`);
						dispatch('closeBLEConnection', deviceId);
						reject({
							errMsg: `该设备无${properti}权限，可能无法使用该功能`,
						});
					} else {
						common.showToast(`获取设备服务失败`);
						dispatch('closeBLEConnection', deviceId);
						reject({
							errMsg: '获取设备服务失败',
						});
					}
				} catch (err) {
					if (err.errCode) {
						common.showToast(bluetooth.bleerrcode(err.errCode));
					} else if (err.errMsg) {
						common.showToast(err.errMsg);
					}
					dispatch('closeBLEConnection', deviceId);
					reject(err);
				}
			});
		},
	},
});

export default store;
